<template>
  <div class="chat-container">
    <!-- 空状态提示 -->
    <div v-if="!props.chatId" class="empty-state">
      <el-empty description="暂无对话">
        <template #description>
          <p>点击左侧"新建对话"按钮开始聊天</p>
        </template>
        <el-button type="primary" size="small" @click="$emit('create-chat')">
          新建对话
        </el-button>
      </el-empty>
    </div>

    <!-- 聊天内容区域 -->
    <template v-else>
      <!-- 聊天记录区域 -->
      <div class="chat-messages" ref="messagesContainer" @scroll="handleScroll">
        <div v-for="(message, index) in messages" :key="index" :class="['message', message.role]">
          <div class="message-content">
            <div v-if="message.thinking" class="thinking-section" v-html="renderMarkdown(message.thinking)"></div>
            <div class="answer-section" v-html="renderMarkdown(message.content)"></div>
          </div>
        </div>
        <!-- 流式响应显示区域 -->
        <div v-if="streaming" class="message ai">
          <div class="message-content">
            <div v-if="currentThinking" class="thinking-section" v-html="renderMarkdown(currentThinking)"></div>
            <div v-if="currentResponse" class="answer-section">
              <span v-html="renderMarkdown(currentResponse)"></span>
              <span class="cursor">|</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="chat-input">
        <input
            v-model="userInput"
            @keyup.enter="!streaming && sendMessage()"
            placeholder="请输入您的问题..."
        >
        <button @click="sendMessage" :disabled="streaming || !userInput.trim()">
          发送
        </button>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import { marked } from 'marked'
import DOMPurify from 'dompurify'

const props = defineProps({
  chatId: {
    type: String,
    required: true,
    default: ''
  }
})

const messages = ref([])
const userInput = ref('')
const streaming = ref(false)
const currentResponse = ref('')
const currentThinking = ref('')
const messagesContainer = ref(null)
const autoScroll = ref(true)

// 渲染 Markdown
const renderMarkdown = (text) => {
  return DOMPurify.sanitize(marked(text || '', { breaks: true, gfm: true }))
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value && autoScroll.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 处理滚动事件
const handleScroll = () => {
  if (messagesContainer.value) {
    const { scrollTop, scrollHeight, clientHeight } = messagesContainer.value
    autoScroll.value = Math.abs(scrollHeight - scrollTop - clientHeight) < 50
  }
}

// 处理流式文本和历史消息的文本解析
const processStreamText = (text) => {
  let processedText = text || ''
  let isThinking = false
  let thinkContent = ''
  let answer = ''

  // 检查是否包含思考内容（使用 <think> 标签）
  if (processedText.startsWith('<think>')) {
    const endIndex = processedText.indexOf('</think>')
    if (endIndex !== -1) {
      // 完整包含 <think> 和 </think>
      thinkContent = processedText.substring(7, endIndex).trim()  // <think> 长度为 7
      answer = processedText.substring(endIndex + 8).trim()  // </think> 长度为 8
      isThinking = false
    } else {
      // 只收到 <think> 的部分，未收到 </think>
      thinkContent = processedText.substring(7).trim()
      isThinking = true
    }
  } else {
    // 没有 <think> 标签，全部视为回答
    answer = processedText.trim()
  }

  console.log('解析结果 - thinking:', thinkContent, 'answer:', answer)  // 调试日志

  return {
    thinking: thinkContent,
    answer: answer,
    isThinking: isThinking
  }
}

// 获取聊天历史
const fetchChatHistory = async () => {
  if (!props.chatId) {
    messages.value = []
    return
  }

  try {
    console.log('开始获取对话历史, chatId:', props.chatId)
    const url = `/ai/getSpringAiChatMemoryByConversationId?conversationId=${encodeURIComponent(props.chatId)}`
    console.log('请求URL:', url)

    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Accept': 'application/json'
      },
      credentials: 'include'
    })

    console.log('历史记录响应状态:', response.status)
    const history = await response.json()
    console.log('获取到的历史记录数据:', history)

    // 清空现有消息
    messages.value = []

    if (Array.isArray(history) && history.length > 0) {
      history.forEach((item, index) => {
        console.log(`处理第 ${index + 1} 条消息:`, item)
        try {
          if (item.type.toLowerCase() === 'user') {
            messages.value.push({
              role: 'user',
              content: item.content
            })
          } else {
            const { thinking, answer } = processStreamText(item.content)
            messages.value.push({
              role: 'ai',
              thinking: thinking || '',
              content: answer || ''
            })
          }
        } catch (e) {
          console.error('处理消息出错:', e, item)
        }
      })
      console.log('历史记录处理完成，消息数:', messages.value.length)
    } else {
      console.log('没有历史记录，显示欢迎消息')
      messages.value.push({
        role: 'ai',
        content: '# 欢迎使用 AI 助手你好！我是您的 AI 助手，很高兴为您服务。请问有什么可以帮助您的吗？'
    })
    }

    await scrollToBottom()
  } catch (error) {
    console.error('获取历史记录失败:', error)
    messages.value = []
    messages.value.push({
      role: 'system',
      content: `**无法加载聊天历史**: ${error.message}`
    })
    await scrollToBottom()
  }
}

// 发送消息
const sendMessage = async () => {
  if (!userInput.value.trim() || streaming.value) return

  const prompt = userInput.value
  userInput.value = ''

  messages.value.push({
    role: 'user',
    content: prompt
  })
  autoScroll.value = true
  await scrollToBottom()

  streaming.value = true
  currentResponse.value = ''
  currentThinking.value = ''
  let buffer = ''
  let isInThinkingSection = false

  try {
    const url = `/ai/chat?prompt=${encodeURIComponent(prompt)}&chatId=${props.chatId}`
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Accept': 'text/plain'
      },
      credentials: 'include'
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const reader = response.body.getReader()
    const decoder = new TextDecoder('utf-8')

    while (true) {
      const { value, done } = await reader.read()
      if (done) break

      const text = decoder.decode(value, { stream: true })
      console.log('收到流式数据:', text)  // 调试日志
      buffer += text

      // 查找 <think> 和 </think> 标签
      if (isInThinkingSection) {
        // 当前在思考部分
        const endIndex = buffer.indexOf('</think>')
        if (endIndex !== -1) {
          // 找到结束标签，提取思考内容
          currentThinking.value = buffer.substring(0, endIndex).trim()
          buffer = buffer.substring(endIndex + 8)  // 移除 <think>...内容</think>
          isInThinkingSection = false
          currentResponse.value = buffer.trim()
        } else {
          // 未找到结束标签，继续累积思考内容
          currentThinking.value = buffer.substring(7).trim()  // 从 <think> 后开始
        }
      } else {
        // 检查是否进入新的思考部分
        if (buffer.startsWith('<think>')) {
          isInThinkingSection = true
          currentThinking.value = buffer.substring(7).trim()  // <think> 长度 7
          currentResponse.value = ''
        } else {
          // 累积回答内容
          currentResponse.value = buffer.trim()
        }
      }

      await scrollToBottom()
    }

    // 处理最终的 buffer
    const { thinking, answer } = processStreamText(buffer)
    if (thinking || answer) {
      messages.value.push({
        role: 'ai',
        thinking: thinking,
        content: answer
      })
    }

  } catch (error) {
    console.error('Error:', error)
    messages.value.push({
      role: 'system',
      content: `**请求失败**: ${error.message}`
    })
  } finally {
    streaming.value = false
    currentResponse.value = ''
    currentThinking.value = ''
    isInThinkingSection = false
    await scrollToBottom()
  }
}

// 监听 chatId 变化
watch(() => props.chatId, (newId, oldId) => {
  console.log('chatId changed:', oldId, '->', newId)
  if (newId) {
    fetchChatHistory()
  }
}, { immediate: true })

onMounted(async () => {
  await fetchChatHistory()
  await scrollToBottom()
})

// 暴露方法给父组件
defineExpose({
  fetchChatHistory
})

defineEmits(['create-chat'])
</script>

<style scoped>
/* 样式代码保持不变，与之前相同 */
.chat-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 6px;
  background-color: #f5f5f5;
  scroll-behavior: smooth;
}

.message {
  margin-bottom: 4px;
  display: flex;
  flex-direction: column;
}

.message.user {
  align-items: flex-end;
}

.message.ai {
  align-items: flex-start;
}

.message-content {
  padding: 6px 10px;
  border-radius: 8px;
  background-color: white;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
  line-height: 1.5;
  font-size: 13px;
  max-width: 80%;
}

.thinking-section {
  background-color: #f5f5f5;
  padding: 4px 8px 4px 24px;
  margin-bottom: 4px;
  border-radius: 6px;
  font-style: italic;
  color: #666;
  position: relative;
  line-height: 1.5;
  font-size: 12px;
}

.thinking-section::before {
  content: "💭";
  position: absolute;
  left: 4px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 12px;
}

.answer-section {
  padding: 3px 8px 3px 24px;
  position: relative;
  line-height: 1.5;
}

.message.ai .answer-section::before {
  content: "🤖";
  position: absolute;
  left: 4px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 12px;
}

.message.user .message-content {
  background-color: #007AFF;
  color: white;
  display: inline-block;
  width: fit-content;
}

.message.user .answer-section {
  padding: 3px 8px;
}

.chat-input {
  display: flex;
  padding: 8px;
  background-color: white;
  border-top: 1px solid #ddd;
  min-height: 40px;
}

input {
  flex: 1;
  padding: 4px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-right: 6px;
  font-size: 13px;
}

button {
  padding: 4px 12px;
  background-color: #007AFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.cursor {
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}

.chat-messages::-webkit-scrollbar {
  width: 4px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 2px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.empty-state {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  text-align: center;
}

.empty-state :deep(.el-empty__description) {
  margin-top: 10px;
}

.empty-state :deep(.el-empty__description p) {
  color: #909399;
  font-size: 14px;
  margin: 10px 0;
}

.empty-state :deep(.el-button) {
  margin-top: 20px;
}

/* Markdown 样式优化 */
:deep(.message-content) {
  /* 标题样式 */
  h1, h2, h3, h4, h5, h6 {
    margin: 8px 0;
    font-weight: bold;
  }
  h1 { font-size: 18px; }
  h2 { font-size: 16px; }
  h3 { font-size: 14px; }

  /* 列表样式 */
  ul, ol {
    padding-left: 20px;
    margin: 8px 0;
  }
  li {
    margin-bottom: 4px;
  }

  /* 代码块样式 */
  pre, code {
    background-color: #f6f8fa;
    border-radius: 4px;
    padding: 2px 4px;
    font-family: 'Consolas', 'Monaco', monospace;
  }
  pre {
    padding: 8px;
    overflow-x: auto;
  }

  /* 行内代码样式 */
  code:not(pre code) {
    padding: 2px 4px;
  }

  /* 引用样式 */
  blockquote {
    border-left: 4px solid #dfe2e5;
    padding: 0 12px;
    color: #6a737d;
    margin: 8px 0;
  }

  /* 链接样式 */
  a {
    color: #0366d6;
    text-decoration: none;
  }
  a:hover {
    text-decoration: underline;
  }
}

@media screen and (max-width: 768px) {
  .chat-container {
    width: 100%;
    height: 100%;
    border: none;
  }

  .message {
    max-width: 99%;
    margin-bottom: 3px;
  }

  .message-content {
    font-size: 12px;
    line-height: 1.4;
    padding: 4px 8px;
  }

  .thinking-section {
    padding: 3px 6px 3px 20px;
    font-size: 11px;
  }

  .answer-section {
    padding: 3px 8px 3px 24px;
    line-height: 1.4;
  }

  .chat-input {
    padding: 6px;
    min-height: 36px;
  }

  input {
    padding: 3px 6px;
  }

  button {
    padding: 3px 10px;
  }

  :deep(.message-content) {
    h1 { font-size: 16px; }
    h2 { font-size: 14px; }
    h3 { font-size: 13px; }
  }
}
</style>
